<template>
  <el-form
    :model="form"
    ref="form"
    :rules="rule"
    status-icon
    label-width="100px"
    label-position="left"
  >
    <p v-show="account.length>0" style="margin-bottom: 5px;">
      点击获取验证码，验证码将发送至账号
      <b>{{'****'+(account.indexOf('@')>=0?account.substr(account.indexOf('@')):account.substr(-4))}}</b>
    </p>
    <el-form-item prop="captcha" label="验证码">
      <el-input v-model="form.captcha" style="width:150px;margin-right: 20px;"></el-input>
      <el-button
        type="primary"
        :disabled="loading"
        :loading="loading"
        @click="sendCaptcha"
      >{{count<60?`(${count})s重新获取`:'获取验证码'}}</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="warning" @click="prevStep">上一步</el-button>
      <el-button type="primary" @click="verifyCaptcha">下一步</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { userAPI } from "@/utils/api.js";
import { mapMutations, mapGetters } from "vuex";
export default {
  data() {
    return {
      loading: false, //点击获取验证码显示加载中 并禁用
      count: 60, //重新获取验证码倒计时
      /* 验证码表单 */
      form: {
        captcha: ""
      },
      //验证规则
      rule: {
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { max: 4, min: 4, message: "验证码长度限制为4位", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      //vuex辅助函数 混入计算属性
      account: "getFrgAccount"
    })
  },
  methods: {
    ...mapMutations({
      saveCaptcha: "saveFrgCaptcha"
    }),
    prevStep() {
      this.$emit("prevStep");
    },
    sendCaptcha() {
      if (this.account) {
        //如果存在account,就执行获取验证码
        this.loading = true;
        let data = {
          token: this.account
        };
        userAPI.common
          .getMessageToken(data)
          .then(res => {
            //console.log(res);
            this.startCount();
          })
          .catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.loading = false; //取消加载和禁用
          });
      }
    },
    startCount() {
      this.timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 60;
          clearInterval(this.timer);
        }
      }, 1000);
    },
    verifyCaptcha() {
      /* 校验验证码规则 */
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveCaptcha(this.form);
          this.$emit("nextStep"); //下一步
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
</style>